package org.card.interceptor;

import org.card.bean.User;
import org.card.service.UserService;
import org.card.util.CookieUtils;
import org.card.util.UserHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by card on 16/3/4.
 */
public class AdminInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserHolder userHolder;

    @Resource
    private UserService userService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String username = CookieUtils.getUsername(request);

        String uri = request.getRequestURI();
        if(uri.equalsIgnoreCase("/admin/login")){
            return true;
        }

        if(username == null) {
            response.sendRedirect("/admin/login");
            return false;
        }

        User user = userService.findByUsername(username);
        if(user == null) {
            response.sendRedirect("/admin/login");
            return false;
        }

        userHolder.setUser(user);



        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        userHolder.remove();
    }
}
